<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();

// 筛选条件
const filter = reactive({
  name: '',
  status: '',
  online: '',
  start: '',
  end: ''
});

// 表格数据
const tableData = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const form = reactive({
  id: '',
  name: '',
  time: [],
  productCount: 0,
  status: '',
  online: '上线'
});
const formRef = ref();
const rules = {
  name: [ { required: true, message: '请输入拼团名称', trigger: 'blur' } ],
  time: [ { required: true, message: '请选择活动时间', trigger: 'change' } ]
};

// mock 数据
const mockList = [
  {
    id: '1',
    name: '春季拼团活动',
    time: '2021-03-02 ~ 2017-03-12',
    productCount: 10,
    status: '进行中',
    online: '上线'
  },
  {
    id: '2',
    name: '春季拼团活动',
    time: '2021-03-02 ~ 2017-03-12',
    productCount: 10,
    status: '进行中',
    online: '上线'
  },
  {
    id: '3',
    name: '春季拼团活动',
    time: '2021-03-02 ~ 2017-03-12',
    productCount: 10,
    status: '已结束',
    online: '上线'
  },
  {
    id: '4',
    name: '春季拼团活动',
    time: '2021-03-02 ~ 2017-03-12',
    productCount: 10,
    status: '已结束',
    online: '上线'
  }
];

function fetchTableData() {
  loading.value = true;
  setTimeout(() => {
    // 模拟筛选和分页
    let list = mockList.filter(item => {
      return (
        (!filter.name || item.name.includes(filter.name)) &&
        (!filter.status || item.status === filter.status) &&
        (!filter.online || item.online === filter.online)
      );
    });
    total.value = list.length;
    tableData.value = list.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
    loading.value = false;
  }, 300);
}

onMounted(fetchTableData);

function handleSearch() {
  currentPage.value = 1;
  fetchTableData();
}
function handleReset() {
  Object.assign(filter, { name: '', status: '', online: '', start: '', end: '' });
  currentPage.value = 1;
  fetchTableData();
}
function handlePageChange(val: number) {
  currentPage.value = val;
  fetchTableData();
}
function handleSizeChange(val: number) {
  pageSize.value = val;
  fetchTableData();
}

function handleCreate() {
  isEdit.value = false;
  Object.assign(form, { id: '', name: '', time: [], productCount: 0, status: '', online: '上线' });
  dialogVisible.value = true;
}
function handleEdit(row: any) {
  router.push(`/operation/group-buy/edit/${row.id}`);
}
async function handleSubmit() {
  await formRef.value.validate();
  if (isEdit.value) {
    // 编辑
    const idx = mockList.findIndex(item => item.id === form.id);
    if (idx > -1) {
      mockList[idx] = { ...form, time: form.time.join(' ~ ') };
      ElMessage.success('编辑成功');
    }
  } else {
    // 新建
    mockList.push({ ...form, id: Date.now() + '', time: form.time.join(' ~ '), status: '进行中', online: '上线' });
    ElMessage.success('新建成功');
  }
  dialogVisible.value = false;
  fetchTableData();
}
async function handleDelete(row: any) {
  await ElMessageBox.confirm('确定要删除该拼团活动吗？', '提示', { type: 'warning' });
  const idx = mockList.findIndex(item => item.id === row.id);
  if (idx > -1) {
    mockList.splice(idx, 1);
    ElMessage.success('删除成功');
    fetchTableData();
  }
}
async function handleOffline(row: any) {
  await ElMessageBox.confirm('确定要下线该拼团活动吗？', '提示', { type: 'warning' });
  const idx = mockList.findIndex(item => item.id === row.id);
  if (idx > -1) {
    mockList[idx].online = '下线';
    ElMessage.success('已下线');
    fetchTableData();
  }
}
</script>

<template>
  <div style="padding: 32px 0; background: #fafafa; min-height: 100vh;">
    <!-- 筛选区 -->
    <el-card style="margin: 0 auto; max-width: 1600px;">
      <el-form :inline="true" :model="filter" class="filter-form" style="margin-bottom: 12px;">
        <el-form-item label="拼团名称">
          <el-input v-model="filter.name" placeholder="请输入内容" clearable style="width: 180px;" />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="filter.status" placeholder="全部" style="width: 140px;">
            <el-option label="全部" value="" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已结束" value="已结束" />
          </el-select>
        </el-form-item>
        <el-form-item label="上线状态">
          <el-select v-model="filter.online" placeholder="全部" style="width: 140px;">
            <el-option label="全部" value="" />
            <el-option label="上线" value="上线" />
            <el-option label="下线" value="下线" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动时间">
          <el-date-picker
            v-model="filter.start"
            type="date"
            placeholder="开始时间"
            style="width: 130px;"
          />
          <span style="margin: 0 8px;">至</span>
          <el-date-picker
            v-model="filter.end"
            type="date"
            placeholder="结束时间"
            style="width: 130px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">检索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="danger" @click="handleCreate">新建拼团</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区 -->
    <el-card style="margin: 32px auto 0; max-width: 1600px;">
      <el-table :data="tableData" border style="width: 100%;" :loading="loading">
        <el-table-column prop="name" label="拼团名称" min-width="180" />
        <el-table-column prop="time" label="活动时间" min-width="220" />
        <el-table-column prop="productCount" label="关联商品数" min-width="120" align="center" />
        <el-table-column prop="status" label="活动状态" min-width="120" align="center" />
        <el-table-column prop="online" label="上线状态" min-width="120" align="center" />
        <el-table-column label="操作" min-width="180" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" link @click="handleOffline(row)">下线</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 16px;">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total, sizes"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50, 100]"
        />
        <span style="color: #d33; font-size: 15px;">当前条件共检索到 {{ total }} 条相关信息</span>
      </div>
    </el-card>

    <!-- 新建/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑拼团' : '新建拼团'" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
        <el-form-item label="拼团名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="活动时间" prop="time">
          <el-date-picker v-model="form.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="关联商品数">
          <el-input-number v-model="form.productCount" :min="0" />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option label="未开始" value="未开始" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已结束" value="已结束" />
          </el-select>
        </el-form-item>
        <el-form-item label="上线状态">
          <el-select v-model="form.online" placeholder="请选择">
            <el-option label="上线" value="上线" />
            <el-option label="下线" value="下线" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}
</style>
